package com.hyq.learn.ai.config;

import io.modelcontextprotocol.server.transport.WebMvcSseServerTransportProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.HandlerFilterFunction;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;

/**
 * @author heyuqin
 * @date 2025/11/14 15:32
 */
@Configuration
public class McpRouterConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(McpRouterConfig.class);

    /**
     * RouterFunction<ServerResponse> 是MCP请求的所有逻辑处理的入口
     */
    @Bean
    public RouterFunction<ServerResponse> loggingRouter(WebMvcSseServerTransportProvider provider) {
        RouterFunction<ServerResponse> router = provider.getRouterFunction();

        HandlerFilterFunction<ServerResponse, ServerResponse> logResponse =
                HandlerFilterFunction.ofResponseProcessor((request, response) -> {
                    LOGGER.info("Incoming request: {} {}", request.method(), request.path());
                    // 这里只是用来表示响应的一个状态，并不包含实际的响应体，所以这里无法做日志的打印
                    LOGGER.info("Outgoing response: status={}", response.statusCode());
                    return response;
                });
        return router.filter(logResponse);
    }

}
